package com.example.springresource01;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;

@SpringBootApplication
public class SpringResource01Application {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, IOException {

        /**
         * 什么是BeanFacotry
         *  -它是ApplicationContext的父接口
         *  -它才是Spring的核心容器，主要的ApplicationContext实现都组合了它的功能
         */
        ConfigurableApplicationContext context = SpringApplication.run(SpringResource01Application.class, args);

        System.out.println("context.getBeanFactory().getClass() = " + context.getBeanFactory().getClass().getName());

        /**
         * BeanFactory能干点啥
         *      -表面上只是用来获取Bean实例，实际上控制反转、基本的依赖注入、直至Bean的生命周期的各种功能，都由他的实现类提供。
         *      -在这一步用反射来获取singletonObjects来查看容器内的单例实例
         */
        Field singletonObjects = DefaultSingletonBeanRegistry.class.getDeclaredField("singletonObjects");
        singletonObjects.setAccessible(true);

        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        Map<String,Object> map = (Map<String, Object>) singletonObjects.get(beanFactory);

        map.forEach((k,v)->{
            System.out.println("k  = " + k );
            System.out.println("v = " + v);
        });

        /**
         * 3. ApplicationContext比BeanFactory多了什么功能
         */

        //国际化
        System.out.println("context.getMessage(\"hi\",null, Locale.CHINA) = " + context.getMessage("hi", null, Locale.CHINA));
        System.out.println("context.getMessage(\"hi\",null, Locale.ENGLISH) = " + context.getMessage("hi", null, Locale.ENGLISH));
        System.out.println("context.getMessage(\"hi\",null, Locale.UK) = " + context.getMessage("hi", null, Locale.UK));

        //
        Resource[] resources = context.getResources("classpath:messages*.properties");
        Arrays.stream(resources).forEach(System.out::println);

        UserService userService = context.getBean(UserService.class);

        userService.register();
    }

}
